[5.1] Custom Error Messages for Unauthorized Access #16601
Closed
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Summary:
After creating a Policy Class for the Current User and a related Eloquent Model, we need to register it with the Gate Class to essentially manage the various (CRUD) operations that the User can perform on that Model.
The
authorize
function implemented in the Gate Class takes in 2 arguments -$ability
[string] indicates what operation the User wants to perform on the Model; while$arguments
[string orIlluminate\Support\Collection
] indicates what error message is to be returned, if the User is not permitted to perform the operation.The method in turn calls the
allow
anddeny
methods implemented in theHandlesAuthorization
trait: returningnull
(access granted) or raising anAuthorizationException
(access denied). The exception is constructed with the default message - "This action is unauthorized.", unless$arguments
was provided to override it.The
deny
method accepts a$message
parameter which is initialized to the default error message. However, the$arguments
to override the default was not being passed down from theauthorize
function as a parameter, while calling thedeny
function. Thus, the default error message could not be changed.Here is the issue.
Solution:
Just calling the
deny
method with the given$arguments
, from the controller, as parameters solves this problem: